package org.jeecg.modules.complain.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.complain.entity.RepairConfig;
import org.jeecg.modules.complain.service.IRepairConfigService;
import org.jeecg.modules.system.entity.SysPosition;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecg.modules.system.service.ISysUserPositionService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @Description: 报修基础配置
* @Author: jeecg-boot
* @Date:   2019-07-29
* @Version: V1.0
*/
@Slf4j
@Api(tags="报修基础配置")
@RestController
@RequestMapping("/b/repairConfig")
public class RepairConfigController {
   @Autowired
   private IRepairConfigService repairConfigService;
   @Autowired
   private ISysPositionService sysPositionService;
   @Autowired
   private ISysUserPositionService sysUserPositionService;
   @Autowired
   private ISysUserRoleService sysUserRoleService;


   /**
     * 分页列表查询
    * @param repairConfig
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "报修基础配置-分页列表查询")
   @ApiOperation(value="报修基础配置-分页列表查询", notes="报修基础配置-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<RepairConfig>> queryPageList(RepairConfig repairConfig,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                    HttpServletRequest req) {
       Result<IPage<RepairConfig>> result = new Result<IPage<RepairConfig>>();
       List<String> officeIds = sysUserRoleService.queryOfficeIds(repairConfig);
       repairConfig.resetValue();
       QueryWrapper<RepairConfig> queryWrapper = QueryGenerator.initQueryWrapper(repairConfig, req.getParameterMap());
        queryWrapper.eq("del_flag",0);
       if (officeIds.size() <=0){
           queryWrapper.eq("depart_id","");
       }else{
           queryWrapper.in("depart_id",officeIds);
       }
        Page<RepairConfig> page = new Page<RepairConfig>(pageNo, pageSize);
        IPage<RepairConfig> pageList = repairConfigService.page(page, queryWrapper);
        List<RepairConfig> records = pageList.getRecords();
        for (RepairConfig rc:records) {
          rc.setReceivePositionArr(Arrays.asList(rc.getReceivePositionCode().split(",")));
          rc.setHandlePositionArr(Arrays.asList(rc.getHandlePositionCode().split(",")));
       }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
   }
   /**
     *   添加
    * @param repairConfig
    * @return
    */
   @AutoLog(value = "报修基础配置-添加")
   @ApiOperation(value="报修基础配置-添加", notes="报修基础配置-添加")
   @PostMapping(value = "/add")
   public Result<RepairConfig> add(@RequestBody Map<String,Object> map) {
       Result<RepairConfig> result = new Result<RepairConfig>();
       RepairConfig repairConfig = new RepairConfig();
       String departId = (String)map.get("departId");
       RepairConfig repairConfigs = repairConfigService.selectConfigByDepartId(departId);
       if (repairConfigs != null){
           repairConfigService.delet(departId);
       }
       repairConfig.setRepairType("PS005");
       repairConfig.setCreateTime(new Date());
       repairConfig.setUpdateDate(new Date());
       if(StringUtils.isEmpty(departId)){
           return  Result.error("部门不能为空");
       }
       repairConfig.setDepartId(departId);
       String repairModel = (String) map.get("repairModel");
       if (repairModel.equals("0")){
           repairConfig.setRepairModel(0);
           Object hd = map.get("handlePositionArr");
           String handlePositionCode = hd.toString().replace("[", "").replace("]", "").replaceAll(" ","");
           Object rp = map.get("receivePositionArr");
           String receivePositionCode = rp.toString().replace("[", "").replace("]", "").replaceAll(" ","");
           List<String> strings = Arrays.asList(handlePositionCode.split(","));
           String handlePositionName = "";
           handlePositionName = sysPositionService.selectByPositionId(strings);
           List<String> recives = Arrays.asList(receivePositionCode.split(","));
           String receivePositionName = "";
           receivePositionName = sysPositionService.selectByPositionId(recives);
           repairConfig.setSendPositionCode(null);
           repairConfig.setSendPositionName(null);
           repairConfig.setSendConfigFlg(0);
           repairConfig.setHandlePositionCode(handlePositionCode);
           repairConfig.setReceivePositionCode(receivePositionCode);
           repairConfig.setReceivePositionName(receivePositionName);
           repairConfig.setHandlePositionName(handlePositionName);
       }else {
           repairConfig.setRepairModel(1);
           Object hd = map.get("handlePositionArr");
           String handlePositionCode = hd.toString().replace("[", "").replace("]", "").replaceAll(" ","");
           Object rp = map.get("receivePositionArr");
           String receivePositionCode = rp.toString().replace("[", "").replace("]", "").replaceAll(" ","");
           repairConfig.setHandlePositionCode(handlePositionCode);
           repairConfig.setReceivePositionCode(receivePositionCode);
           List<String> strings = Arrays.asList(handlePositionCode.split(","));
           String handlePositionName = "";
           handlePositionName  = sysPositionService.selectByPositionId(strings);
           List<String> recives = Arrays.asList(receivePositionCode.split(","));
           String receivePositionName = "";
           receivePositionName = sysPositionService.selectByPositionId(recives);
           repairConfig.setReceivePositionName(receivePositionName);
           repairConfig.setHandlePositionName(handlePositionName);
       }
           repairConfigService.save(repairConfig);
           result.success("添加成功！");
           return result;
   }

   /**
     *  编辑
    * @param repairConfig
    * @return
    */
   @AutoLog(value = "报修基础配置-编辑")
   @ApiOperation(value="报修基础配置-编辑", notes="报修基础配置-编辑")
   @PutMapping(value = "/edit")
   public Result<RepairConfig> edit(@RequestBody Map<String,Object>map) {
       Result<RepairConfig> result = new Result<RepairConfig>();
       Object handlePositionCode = map.get("handlePositionArr");
       String s = handlePositionCode.toString().replace("[", "").replace("]", "").replaceAll(" ", "");
       Object receivePositionCode = map.get("receivePositionArr");
       String s1 = receivePositionCode.toString().replace("[", "").replace("]", "").replaceAll(" ", "");
       String departId = (String) map.get("departId");
       String id =(String) map.get("id");
       RepairConfig repairConfig = new RepairConfig();
       repairConfig.setDepartId(departId);
       repairConfig.setReceivePositionCode(s1);
       repairConfig.setHandlePositionCode(s);
       List<String> strings = Arrays.asList(s.split(","));
       String handlePositionName = "";
       handlePositionName = sysPositionService.selectByPositionId(strings);
       List<String> recives = Arrays.asList(s1.split(","));
       String reciveName = "";
       reciveName= sysPositionService.selectByPositionId(recives);
       repairConfig.setId(id);
       repairConfig.setHandlePositionName(handlePositionName);
       repairConfig.setReceivePositionName(reciveName);
       RepairConfig repairConfigEntity = repairConfigService.getById(id);
       if(repairConfigEntity==null) {
           result.error500("未找到对应实体");
       }else {
           boolean ok = repairConfigService.updateById(repairConfig);
           //TODO 返回false说明什么？
           if(ok) {
               result.success("修改成功!");
           }
       }
       return result;
   }

   /**
     *   通过id删除
    * @param id
    * @return
    */
   @AutoLog(value = "报修基础配置-通过id删除")
   @ApiOperation(value="报修基础配置-通过id删除", notes="报修基础配置-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       try {
           repairConfigService.removeById(id);
       } catch (Exception e) {
           log.error("删除失败",e.getMessage());
           return Result.error("删除失败!");
       }
       return Result.ok("删除成功!");
   }
   /**
     *  批量删除
    * @param ids
    * @return
    */
   @AutoLog(value = "报修基础配置-批量删除")
   @ApiOperation(value="报修基础配置-批量删除", notes="报修基础配置-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<RepairConfig> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       Result<RepairConfig> result = new Result<RepairConfig>();
       if(ids==null || "".equals(ids.trim())) {
           result.error500("参数不识别！");
       }else {
           this.repairConfigService.removeByIds(Arrays.asList(ids.split(",")));
           result.success("删除成功!");
       }
       return result;
   }
   /**
     * 通过id查询
    * @param id
    * @return
    */
   @AutoLog(value = "报修基础配置-通过id查询")
   @ApiOperation(value="报修基础配置-通过id查询", notes="报修基础配置-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<RepairConfig> queryById(@RequestParam(name="id",required=true) String id) {
       Result<RepairConfig> result = new Result<RepairConfig>();
       RepairConfig repairConfig = repairConfigService.getById(id);
       if(repairConfig==null) {
           Result.error("未找到对应实体");
       }else {
           result.setResult(repairConfig);
           result.setSuccess(true);
       }
       return result;
   }

 /**
     * 导出excel
  *
  * @param request
  * @param response
  */
 @RequestMapping(value = "/exportXls")
 public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
     // Step.1 组装查询条件
     QueryWrapper<RepairConfig> queryWrapper = null;
     try {
         String paramsStr = request.getParameter("paramsStr");
         if (oConvertUtils.isNotEmpty(paramsStr)) {
             String deString = URLDecoder.decode(paramsStr, "UTF-8");
             RepairConfig repairConfig = JSON.parseObject(deString, RepairConfig.class);
             queryWrapper = QueryGenerator.initQueryWrapper(repairConfig, request.getParameterMap());
         }
     } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
     }
     //Step.2 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     List<RepairConfig> pageList = repairConfigService.list(queryWrapper);
     //导出文件名称
     mv.addObject(NormalExcelConstants.FILE_NAME, "报修基础配置列表");
     mv.addObject(NormalExcelConstants.CLASS, RepairConfig.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("报修基础配置列表数据", "导出人:Jeecg", "导出信息"));
     mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
     return mv;
 }

 /**
     * 通过excel导入数据
  *
  * @param request
  * @param response
  * @return
  */
 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         MultipartFile file = entity.getValue();// 获取上传文件对象
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setNeedSave(true);
         try {
             List<RepairConfig> listRepairConfigs = ExcelImportUtil.importExcel(file.getInputStream(), RepairConfig.class, params);
             repairConfigService.saveBatch(listRepairConfigs);
             return Result.ok("文件导入成功！数据行数:" + listRepairConfigs.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.ok("文件导入失败！");
 }

    /**
     * 依据管理处ID查找所有的维修职位
     * param：departId
     */
    @RequestMapping("getPositionByDepartId")
    public Result<List<SysPosition>> getPositionByDepartId(@RequestParam(name = "projectId") String projectId,
                                                           @Param("userId")String userId){
        Result<List<SysPosition>> result = new Result<>();
        if (StringUtils.isEmpty(projectId)){
            return Result.error("请选择项目");
        }
        //获取该项目管理处ID
        String  departId = repairConfigService.getDepartIdByProjectId(projectId);
        RepairConfig repairConfig = repairConfigService.selectConfigByDepartId(departId);
        LoginUser loginUser = SsoUtil.getLoginUser();
        userId = loginUser.getId();
        if (null == repairConfig){
            return  null;
        }
        String handlePositionCode = repairConfig.getHandlePositionCode();
        List<String> codeList = Arrays.asList(handlePositionCode.split(","));
        List<SysPosition> sysPositions = repairConfigService.selectByDepartId(departId,codeList,userId);
        result.setResult(sysPositions);
        return  result;
    }
    /**
     * 依据管理处ID拿所有管理处下的项目
     * param departId
     */
    @RequestMapping("getConfigByDepartId")
    public Result<List<RepairConfig>> getConfigByDepartId(String departId){
         Result<List<RepairConfig>> result = new Result<>();
        if (StringUtils.isEmpty(departId)){
            return  result.error500("请选择管理处");
        }
        List<RepairConfig> repairConfigList = repairConfigService.findByDepartId(departId);
        result.setResult(repairConfigList);
        return result;
     }
    /**
     * 查询所有可配置岗位
     */
    @RequestMapping("getPosition")
    public Result<List<SysPosition> > getPosition(){
        Result<List<SysPosition> > result = new Result<>();
        List<SysPosition> list = sysPositionService.list();
        result.setResult(list);
        return result;
    }
}
